package com.masterclient.app.businessmodule.vipmodule.activity;

import android.content.Intent;
import android.os.Bundle;
import android.support.v4.widget.NestedScrollView;
import android.text.Html;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.eoner.baselib.utils.toast.ToastUtil;
import com.eoner.baselib.widget.navgation.FCNavigationBar;
import com.eoner.baselibrary.utils.GlideUtil;
import com.eoner.baselibrary.utils.Utils;
import com.masterclient.app.R;
import com.masterclient.app.base.FCBusinessActivity;
import com.masterclient.app.businessmodule.vipmodule.bean.Products;
import com.masterclient.app.businessmodule.vipmodule.bean.SellerOrderDetail;
import com.masterclient.app.businessmodule.vipmodule.persenter.SellerDetailContract;
import com.masterclient.app.businessmodule.vipmodule.persenter.SellerDetailPresenter;
import com.masterclient.app.modules.aftersale.LogistInfoActivity;
import com.masterclient.app.utils.CommonUtil;
import com.masterclient.app.widget.CircleImage;
import com.masterclient.app.widget.CommonDialog;

import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * 零售订单-订单详细
 */
public class SaleOrderDetailActivity extends FCBusinessActivity<SellerDetailPresenter> implements SellerDetailContract.View {
    @BindView(R.id.status_iv)
    ImageView statusIv;
    @BindView(R.id.status_tv)
    TextView statusTv;
    @BindView(R.id.explain_tv)
    TextView explainTv;
    @BindView(R.id.address_iv)
    ImageView addressIv;
    @BindView(R.id.nick_tv)
    TextView nickTv;
    @BindView(R.id.address_tv)
    TextView addressTv;
    @BindView(R.id.head_iv)
    CircleImage headIv;
    @BindView(R.id.name_tv)
    TextView nameTv;
    @BindView(R.id.agent_tv)
    TextView agentTv;
    @BindView(R.id.container_product)
    LinearLayout containerProduct;
    @BindView(R.id.container_summary)
    LinearLayout containerSummary;
    @BindView(R.id.container_content)
    LinearLayout containerContent;
    @BindView(R.id.beizhu_tv)
    TextView beizhuTv;
    @BindView(R.id.shifu)
    TextView shifu;
    @BindView(R.id.yfh_tv)
    TextView yfhTv;
    @BindView(R.id.num_tv)
    TextView numTv;
    @BindView(R.id.amount_tv)
    TextView amountTv;
    @BindView(R.id.sfk_tv)
    TextView sfkTv;
    @BindView(R.id.btn_tv)
    TextView btnTv;
    @BindView(R.id.tuik_tv)
    TextView tuikTv;
    @BindView(R.id.tkje_view)
    FrameLayout tkjeView;
    @BindView(R.id.yongjin_tv)
    TextView yongjinTv;
    @BindView(R.id.xjyj_view)
    FrameLayout xjyjView;
    @BindView(R.id.daoztv)
    TextView daoztv;
    @BindView(R.id.srdz_view)
    FrameLayout srdzView;
    @BindView(R.id.b_tv)
    TextView bTv;
    @BindView(R.id.n_tv)
    TextView nTv;
    @BindView(R.id.root_view)
    NestedScrollView rootView;
    @BindView(R.id.error_iv)
    ImageView errorIv;
    @BindView(R.id.error_tv)
    TextView errorTv;
    @BindView(R.id.empty_view)
    LinearLayout emptyView;
    private int scene = 1;
    private int status;
    private String order_no;
    private String mobile;
    private String id;

    @Override
    protected int requireGetLayoutId() {
        return R.layout.activity_sale_detail;
    }

    @Override
    protected void requireSetCustomNavigationBar(FCNavigationBar navigationBar) {
        navigationBar.setTitle("订单详情");
    }

    @Override
    protected void requireInitUIAndData(Bundle savedInstanceState) {
        status = getIntent().getIntExtra("status", 1);
        order_no = getIntent().getStringExtra("order_no");
       // if (9 == status)// 已移交订单
      //      scene = 2;
        mPresenter.sellerOrderDetail(order_no, scene);
        Utils.setDin(amountTv, this);
        Utils.setDin(sfkTv, this);
        Utils.setDin(tuikTv, this);
        Utils.setDin(daoztv, this);
        Utils.setDin(yongjinTv, this);
    }

    @OnClick({R.id.btn_tv, R.id.agent_tv,R.id.empty_view})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.btn_tv:
                String text = btnTv.getText().toString();
                if ("立即发货".equals(text))
                    mPresenter.sellerOrderPush(id);
                else if ("查看物流".equals(text))
                    startLogisActivity();
                else if ("立即补货".equals(text))
                    showCommonDialog("请前往葵花子APP补货","确定","取消");
                break;
            case R.id.agent_tv:
                if (!TextUtils.isEmpty(mobile))
                    CommonUtil.copy(this, mobile);
                break;
            case R.id.empty_view:
                rootView.setVisibility(View.GONE);
                emptyView.setVisibility(View.GONE);
                mPresenter.sellerOrderDetail(order_no, scene);
                break;
        }
    }

    @Override
    public void succ(SellerOrderDetail bean) {
        if (null != bean)
            setOrder(bean);
    }

    @Override
    public void error(String error) {
        emptyView.setVisibility(View.VISIBLE);
        rootView.setVisibility(View.GONE);
        errorTv.setText(error);
    }

    // 立即发货接口返回
    @Override
    public void orderPushsucc(String msg) {
        ToastUtil.showToast(msg);
        // 刷新订单详情
        mPresenter.sellerOrderDetail(order_no, scene);
    }

    /**
     * 设置订单详情信息
     *
     * @param sellerOrderDetail
     */
    private void setOrder(SellerOrderDetail sellerOrderDetail) {
        emptyView.setVisibility(View.GONE);
        rootView.setVisibility(View.VISIBLE);
        status = sellerOrderDetail.getStatus();
        id = sellerOrderDetail.getId();
        // 按钮信息
        SellerOrderDetail.ButtonBean buttonBean = sellerOrderDetail.getButton();
        setBtn(buttonBean);
        // 物流信息
        SellerOrderDetail.AddressBean addressBean = sellerOrderDetail.getAddress();
        String name = addressBean.getReceiver_name();
        String phone = addressBean.getReceiver_phone();
        String address = addressBean.getReceiver_address();
        nickTv.setText(name + "　" + phone);
        addressTv.setText(address);
        // 用户信息
        SellerOrderDetail.BuyerInfoBean buyerInfoBean = sellerOrderDetail.getBuyer_info();
        String headImg = buyerInfoBean.getShow_headimgurl();
        if (null != headImg)
            GlideUtil.displayImage(this, headImg, headIv, R.mipmap.user_head_default_icon);
        nameTv.setText(buyerInfoBean.getShow_name());
        int level = buyerInfoBean.getLevel();
        mobile = buyerInfoBean.getMobile();
        String text = "<font color=\"#333333\">" + CommonUtil.getLevetText(level) + "</font>　" + mobile;
        agentTv.setText(Html.fromHtml(text));
        // 商品信息
        containerProduct.removeAllViews();
        List<Products> productsList = sellerOrderDetail.getProducts();
        for (Products products : productsList) {
            View view = addProductItem(products);
            containerProduct.addView(view);
        }
        String remark = sellerOrderDetail.getOrder_remark();
        if (!TextUtils.isEmpty(remark)) {
            beizhuTv.setText(remark);
            nTv.setText(remark.length()+"/70");
        }
        // 优惠信息
        List<SellerOrderDetail.SummaryInfoBean> summaryInfoBeans = sellerOrderDetail.getSummary_info();
        containerSummary.removeAllViews();
        if (null != sellerOrderDetail) {
            for (SellerOrderDetail.SummaryInfoBean summaryInfoBean : summaryInfoBeans) {
                View view = addSummaryItem(summaryInfoBean);
                if (null != view)
                    containerSummary.addView(view);
            }
        }

        numTv.setText("共 " + sellerOrderDetail.getProduct_num() + " 件产品");
        amountTv.setText("¥ " + sellerOrderDetail.getSubTotal());
        sfkTv.setText("¥" + sellerOrderDetail.getSubTotal());
        // 添加订单编号信息
        List<SellerOrderDetail.ContentArrBean> contentArrBeanS = sellerOrderDetail.getContent_arr();
        containerContent.removeAllViews();
        if (null != contentArrBeanS) {
            for (SellerOrderDetail.ContentArrBean contentArrBean : contentArrBeanS) {
                View view = addContentItem(contentArrBean);
                containerContent.addView(view);
            }
        }
        // 退款
        String refund_amount = sellerOrderDetail.getRefund_amount();
        if (!"0".equals(refund_amount)) {
            tkjeView.setVisibility(View.VISIBLE);
            tuikTv.setText("¥ " + refund_amount);
        }
        // 收入到账
        String income = sellerOrderDetail.getIncome();
        if (!"0".equals(income)) {
            srdzView.setVisibility(View.VISIBLE);
            daoztv.setText("¥ " + income);
        }
        // 下级佣金
        String commission = sellerOrderDetail.getCommission();
        if (!"0".equals(commission)) {
            xjyjView.setVisibility(View.VISIBLE);
            yongjinTv.setText("¥ " + commission);
        }
        // 状态信息
        statusIv.setImageResource(R.drawable.icon_order_dfh);
        SellerOrderDetail.TipBean tipBean = sellerOrderDetail.getTip();
        statusTv.setText(tipBean.getLabel());
        explainTv.setText(tipBean.getText());
        shifu.setText("实付:");
        if (status == 0) {// 待付款
            shifu.setText("金额:");
            statusIv.setImageResource(R.drawable.icon_order_unpay);
        } else if (status == 3) {// 已关闭
            statusTv.setTextColor(getResources().getColor(R.color.color_F1444D));
            statusIv.setImageResource(R.drawable.icon_order_close);
        } else if (status == 8) {// 已完成订单
            statusIv.setImageResource(R.drawable.icon_complete);
        } else if (status == 9) {// 已移交订单 退款完成
            statusIv.setImageResource(R.drawable.icon_complete);
        }
    }

    /**
     * 设置按钮文字
     *
     * @param buttonBean
     */
    private void setBtn(SellerOrderDetail.ButtonBean buttonBean) {
        int replenish_btn = buttonBean.getReplenish_btn();// 补货
        int delivery_btn = buttonBean.getDelivery_btn();// 发货
        int view_track_btn = buttonBean.getView_track_btn();// 物流
        if (status == 1) {// 待发货
            if (replenish_btn == 0 && delivery_btn == 0) {
                yfhTv.setVisibility(View.VISIBLE);
            } else if (replenish_btn == 1) {
                btnTv.setVisibility(View.VISIBLE);
                btnTv.setText("立即补货");
            } else if (delivery_btn == 1) {
                btnTv.setVisibility(View.VISIBLE);
                btnTv.setText("立即发货");
            }
        } else {
            if (view_track_btn == 1) {
                btnTv.setVisibility(View.VISIBLE);
                btnTv.setText("查看物流");
            }
        }

    }

    /**
     * @return 动态添加产品信息
     */
    private View addProductItem(Products products) {
        View view = LayoutInflater.from(this).inflate(R.layout.detail_product_item, null);
        ImageView imageView = view.findViewById(R.id.product_iv);
        String img = products.getImage();
        if (null != img)
            GlideUtil.displayImage(this, img, imageView, R.drawable.product_default);
        TextView nameTv = view.findViewById(R.id.title_tv);
        nameTv.setText(products.getName());
        TextView priceTv = view.findViewById(R.id.price_tv);
        priceTv.setText("¥ " + products.getPrice());
        TextView numTv = view.findViewById(R.id.num_tv);
        numTv.setText("X " + products.getBuy_qty());
        Utils.setDin(priceTv, this);
        Utils.setDin(numTv, this);
        TextView specificationsTv = view.findViewById(R.id.specifications_tv);
        specificationsTv.setText(products.getAttribute_desc());
        String refund = products.getRefund_qty();
        if (!TextUtils.isEmpty(refund) && !"0".equals(refund)) {
            TextView tkTv = view.findViewById(R.id.tk_tv);
            tkTv.setText("已退款x " + refund);
        }
        return view;
    }

    /**
     * 添加优惠信息
     *
     * @param summaryInfoBean
     * @return
     */
    private View addSummaryItem(SellerOrderDetail.SummaryInfoBean summaryInfoBean) {
        View view = LayoutInflater.from(this).inflate(R.layout.summary_item, null);
        TextView labelTv = view.findViewById(R.id.label_tv);
        TextView totalTv = view.findViewById(R.id.total_tv);
        String label = summaryInfoBean.getLabel();
        String text = summaryInfoBean.getText();
      //  if ("0".equals(text))
      //      return null;
        if (label.length() == 1)
            label = "　　　" + label;
        else if (label.length() == 2)
            label = "　　" + label;
        else if (label.length() == 3)
            label = "　" + label;
        labelTv.setText(label);
        if("会员折扣".equals(label)||label.contains("优惠")){
            totalTv.setText("-¥ " + text);
        }else {
            totalTv.setText("¥ " + text);
        }
        Utils.setDin(totalTv, this);
        return view;
    }

    /**
     * 添加订单编号信息
     *
     * @param contentArrBean
     * @return
     */
    private View addContentItem(SellerOrderDetail.ContentArrBean contentArrBean) {
        View view = LayoutInflater.from(this).inflate(R.layout.detail_content_item, null);
        TextView labelTv = view.findViewById(R.id.label_tv);
        TextView textTv = view.findViewById(R.id.text_tv);

        String label = contentArrBean.getLabel();
        String text = contentArrBean.getText();
        boolean copyable = contentArrBean.isCopyable();
        labelTv.setText(label);
        textTv.setText(text);
        if (copyable) {
            textTv.setCompoundDrawablesWithIntrinsicBounds(0, 0, R.drawable.icon_copy, 0);
            view.setOnClickListener(v -> CommonUtil.copy(SaleOrderDetailActivity.this, text));
        }
        return view;
    }

    /**
     * 跳转到查看物流
     */
    private void startLogisActivity(){
        Bundle bundle = new Bundle();
        bundle.putString("order_id",id);
        bundle.putString("track_no","");
        bundle.putString("biz_type","1");
        bundle.putBoolean("showKefu",false);
        Intent intent = new Intent(mContext, LogistInfoActivity.class);
        intent.putExtras(bundle);
        startActivity(intent);
    }

    /**
     * 显示dialog
     */
    private void showCommonDialog(String title, String confirmTxt, String cancelTxt) {
        new CommonDialog.Builder(mContext)
                .setTitle(title)
                .setOnConfirmClickListener(confirmTxt, () -> CommonUtil.openUrl(SaleOrderDetailActivity.this,
                        "xrkb://com.flowerbusiness.app/cart?order_id="+id))
                .setOnCancelClickListener(cancelTxt, null)
                .createDialog().show();
    }
}
